﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;

namespace Tizer.Core.Repository
{
    /// <summary>
    /// Хранилище стран
    /// </summary>
    public class CountryRepository : BaseRepository<Country>
    {
        public CountryRepository(ObjectContext context)
            : base(context)
        {
        }

        public CountryRepository()
        {
        }

        /// <summary>
        /// Получить сущность по Id
        /// </summary>
        /// <returns>Сущность</returns>
        public Country GetById(int id)
        {
            return ObjectSet.SingleOrDefault(e => e.ID == id);
        }

        /// <summary>
        /// Удалить 
        /// </summary>
        /// <param name="id">ID</param>
        public void Delete(int id)
        {
            Country country = Single(x => x.ID == id);
            if (country == null) return;

            // обнуляем все города
            using (var cityRepository = new CityRepository(Context))
            {
                var cityList = cityRepository.GetQuery().Where(x => x.CountryID == id);
                foreach (var city in cityList)
                {
                    city.Country = null;
                }
                cityRepository.SaveChanges();
            }
            country.Cities = null;

            // обнуляеем аккаунты
            using (var accountRepository = new AccountRepository(Context))
            {
                var accountList = accountRepository.GetQuery().Where(x => x.CountryID == id);
                foreach (var account in accountList)
                {
                    account.City = null;
                }
                accountRepository.SaveChanges();
            }
            country.Accounts = null;

            // обнуляем рекламу
            using (var outdoorSideRepository = new OutdoorSideRepository(Context))
            {
                var outdoorList = outdoorSideRepository.GetQuery().Where(x => x.CountryID == id);
                foreach (var outdoorSide in outdoorList)
                {
                    outdoorSide.Country = null;
                }
                outdoorSideRepository.SaveChanges();
            }
            country.OutdoorSides = null;

            Delete(country);
            SaveChanges();
        }
    }
}
